using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Interactivity;
using Avalonia.Threading;
using AvaMaid.Neo.Messages;
using CommunityToolkit.Mvvm.Messaging;
using DebounceThrottle;
using FanaticGene.AvaloniaMaid.Core;
using System;
using System.Diagnostics;
using System.IO;

namespace AvaMaid.Neo.Views
{
    public partial class ControlThemeView : UserControl, IRecipient<LoadCodeEventArgs>
    {
        private DebounceDispatcher _dispatcher = new DebounceDispatcher(TimeSpan.FromMilliseconds(200));
        public ControlThemeView()
        {
            InitializeComponent();
            WeakReferenceMessenger.Default.Register(this);
 
        }
        public void Receive(LoadCodeEventArgs message)
        {
            Dispatcher.UIThread.Invoke(() =>
            {
                //PART_AvalonTextEditor.Text = message.Code;
            });
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var text = (sender as TextBox).Text;
            _dispatcher.Debounce(() =>
            {
                WeakReferenceMessenger.Default.Send(new SearchTextChangedEventArgs() { Sender = this, Text = text });
            });
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBox = sender as ListBox;
            if (listBox == null) return;
            var selected = listBox.SelectedItem as CodeUri;
            if (selected == null) return;
            PART_AvalonTextEditor.Text = File.ReadAllText(selected.FullPath);
        }

        private async void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (Avalonia.Application.Current.ApplicationLifetime is ClassicDesktopStyleApplicationLifetime window)
            {
                await window.MainWindow.Clipboard.SetTextAsync(PART_AvalonTextEditor.SelectedText);
            }
        }

    
    }
}
